import time

class TimeLen:
	def __init__(self):
		self.tmphash = {}
		self.sessionSeg = 600
		self.STDTIME = 30

	def ComputeTime(self, skey, FHin, sessionLen=False, stdtime=False):
		''' skey: session key, etc: sessionType, id, ip, we use seesionType and id as sessionKey.
 sessionLen: every two behavor in sessionLen secs is in the same session.
 FHin: TimeLen computes based on File Stream. FHin must be sorted by skey. TimeSign should be last Seg of line in FHin
 stdtime: length of a single behavor.'''
		####### Attention: A Session means: 1. Active Process in sessionLen sec. 2. the same elements in skey  ######
		if sessionLen: self.sessionSeg = sessionLen
		if stdtime: self.STDTIME = stdtime
		print self.sessionSeg, self.STDTIME

		for line in FHin:
			lines = line.strip().split("\t")
			if not lines[-2].isdigit(): continue
			x = "\t".join(map(lambda m: lines[int(m)], skey))

			if self.tmphash:
				if self.tmphash.has_key(x):
					timeAdd = int(lines[-2]) - self.tmphash.values()[0][0]
					#print lines,'::::::',timeAdd
					#print '::::::',timeAdd
					if timeAdd > self.sessionSeg:
						yield self.tmphash.keys()[0], self.tmphash.values()[0][0], self.tmphash.values()[0][1]
						self.tmphash.clear()
						######################  EpochTime   len ############
						self.tmphash[x] = [int(lines[-2]), self.STDTIME]
					else:
						self.tmphash[x][0], self.tmphash[x][1] = int(lines[-2]), self.tmphash[x][1]+timeAdd
				else:
					yield self.tmphash.keys()[0], self.tmphash.values()[0][0], self.tmphash.values()[0][1]
					self.tmphash.clear()
					self.tmphash[x] = [int(lines[-2]), self.STDTIME]
			else:
				self.tmphash[x] = [int(lines[-2]), self.STDTIME]
		else:
			if self.tmphash:
				yield self.tmphash.keys()[0], self.tmphash.values()[0][0], self.tmphash.values()[0][1]
				self.tmphash.clear()


